package com.bbx.taxi.client.Bean.Message;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Handler;

import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.util.LogUtils;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Activity.Wallet.CouponActivity;
import com.bbx.taxi.client.Activity.Menu.MyOrderActivity;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.DB.JmsgDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderingDB;
import com.bbx.taxi.client.Listener.MsgBroadcastReceiver;
import com.bbx.taxi.client.Task.MyOrderTask;
import com.bbx.taxi.client.Task.MyOrderTask.OnOrderFinishToMessageListener;
import com.bbx.taxi.client.Task.MyOrderingTask;
import com.bbx.taxi.client.Task.MyOrderingTask.OnOrderingFinishToMessageListener;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.Util.IsSnQiangDan;
import com.bbx.taxi.client.Util.ToCity2;

/**
 * 在线消息
 */
public class Online implements OnOrderingFinishToMessageListener ,OnOrderFinishToMessageListener{
	public MsgBroadcastReceiver mMsgBroadcastReceiver;
	public Context context;
	/** 异常的消息 */
	public ArrayList<ProcessingMessageBean> list_abnormal = new ArrayList<ProcessingMessageBean>();

	public Online() {
		mMsgBroadcastReceiver = new MsgBroadcastReceiver();
	}

	/**
	 * 在线消息
	 */
	public void onOnline(Context context, JSONObject data) {
		this.context = context;
		LogUtils.e("有在线消息进来" + data.toString());
		JSONObject jmsg = null;
		int type = -1;
		try {
			jmsg = data.getJSONObject(GMsg.msg_jmsg);
			type = Integer.parseInt(jmsg.getString(GMsg.msg_type));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Msgs.Data msgs_data = null;
		JSONObject jmsg_data = null;
		try {
			jmsg_data = new JSONObject(jmsg.getString(GMsg.msg_data));
			msgs_data = (Msgs.Data) new JsonBuild().getData(Msgs.Data.class,
					jmsg_data.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		onProcessingMessage(context, type, jmsg_data.toString(), true, data);
		if (msgs_data != null) {
			// 存储在线消息数据
			JmsgDB db_jmsg = new JmsgDB();
			String order_id = msgs_data.getOrder_id();
			String time = "";
			try {
				time = DateFormat.getTime(Long.parseLong(jmsg
						.getString(GMsg.msg_time)));
			} catch (Exception e) {
			}
			String json = jmsg.toString();
			db_jmsg.onWrite(order_id, time, type, json);

		}
	}
	public synchronized void onProcessingMessage(final Context context, final int type,
			final String jmsg_data, final boolean isOnline, final JSONObject data) {
		new Handler(MyApplication.getInstance().getApplicationContext().getMainLooper()).postDelayed(new Runnable() {
			
			@Override
			public void run() {
				onProcessingMessage2(context, type, jmsg_data, isOnline, data);
			}
		}, 1000);
	}
	/**
	 * 处理在线消息跟离线消息
	 */
	public void onProcessingMessage2(Context context, int type,
			String jmsg_data, boolean isOnline, JSONObject data) {
		this.context = context;
		LogUtils.e("类型为" + type);
		String title="";
		MyOrderingDB db_myordering = new MyOrderingDB();// 我的进行中的订单数据库
		MyOrderDB db_myorder = new MyOrderDB();// 我的全部订单数据库
		Msgs.Data msgs_data = (Msgs.Data) new JsonBuild().getData(
				Msgs.Data.class, jmsg_data.toString());
		switch (type) {
		case GMsg.ONLINE_PAIDAN:
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int order_status = msgs_data.getOrder_status();
				String driver_id = msgs_data.getDriver_id();
				String driver_name = msgs_data.getDriver_name();
				String car_NO = msgs_data.getCar_NO();
				String driver_phone = msgs_data.getDriver_phone();
				double driver_start = msgs_data.getDriver_star();
				db_myordering.onUpdate(order_id, order_status, driver_id,
						driver_name, car_NO, driver_phone, driver_start);
				db_myorder.onUpdate(order_id, order_status, driver_id,
						driver_name, car_NO, driver_phone, driver_start);
			}
			onisFindOrdering(db_myordering, type, msgs_data, data, jmsg_data);
			// setTitle(context, type,
			// db_myordering.onReadDB_ing(context,
			// msgs_data.getOrder_id()),msgs_data.getOrder_id());
			// sendBroadcast(context, GMsg.ONLINE_PAIDAN, null, jmsg_data);
			break;
		case GMsg.ONLINE_CANCEL:
		case GMsg.ONLINE_KF_CANCEL:
			LogUtils.e("", "您有订单被取消");
			// 取消类型
			String cancel_type = "";
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
				cancel_type = msgs_data.getType();
			}
			// 0为客户端取消，则不通知,,【暂时不用】
			if (cancel_type != null && cancel_type.equals("？")) {
			} else {
				onisFindOrdering(db_myordering, type, msgs_data, data,
						jmsg_data);
				// setTitle(context, type,
				// db_myordering.onReadDB_ing(context,
				// msgs_data.getOrder_id()),msgs_data.getOrder_id());
				// sendBroadcast(context, type, data.toString(), jmsg_data);
			}
			break;
		case GMsg.ONLINE_GAIPAI:
		case GMsg.ONLINE_KF_GAIPAIL:
		case GMsg.ONLINE_SJ_GAIPAIL: 
			LogUtils.e("", "您有一个订单被改派");
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
			}
			onisFindOrdering(db_myordering, type, msgs_data, data, jmsg_data);
			// setTitle(context, type,
			// db_myordering.onReadDB_ing(context,
			// msgs_data.getOrder_id()),msgs_data.getOrder_id());
			// sendBroadcast(context, type, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_RELOGIN:
			// 离线消息不处理登陆问题
			if (!isOnline)
				return;
			title = context.getString(R.string.notification_relogin);
			LogUtils.e("", "重新登录");
			DataCleanManager.cleanDatabases(context);
			DataCleanManager.cleanSharedPreference(context);
			DataCleanManager.cleanFiles(context);
			DataCleanManager.cleanExternalCache(context);
			sendBroadcast(context, GMsg.ONLINE_RELOGIN, null, jmsg_data);
			showNotification(context, title, type, null);
			break;
		case GMsg.ONLINE_ONCAR:
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
			}
			onisFindOrdering(db_myordering, type, msgs_data, data, jmsg_data);
			// setTitle(context, type,
			// db_myordering.onReadDB_ing(context,
			// msgs_data.getOrder_id()),msgs_data.getOrder_id());
			// sendBroadcast(context, GMsg.ONLINE_ONCAR, data.toString(),
			// jmsg_data);
			break;
		case GMsg.ONLINE_OFFCAR:
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
			}
			onisFindOrder(db_myorder, type, msgs_data, data, jmsg_data);
			// setTitle(context, type,
			// db_myorder.onReadDB(context,
			// msgs_data.getOrder_id()),msgs_data.getOrder_id());
			// sendBroadcast(context, GMsg.ONLINE_OFFCAR, data.toString(),
			// jmsg_data);
			break;
		case GMsg.ONLINE_FINISH:
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
			}
			// 暂时不需要通知跟消息列表，下次打开的时候记得去消息列表打开消息存储
			// setTitle(context, type,
			// db_myorder.onReadDB(context,
			// msgs_data.getOrder_id()),msgs_data.getOrder_id());
			sendBroadcast(context, GMsg.ONLINE_FINISH, data.toString(),
					jmsg_data);
			if (OrderEvaluationActivity2.jmsg_data != null) {
				OrderEvaluationActivity2.jmsg_data = jmsg_data;
			}
			break;
		case GMsg.ONLINE_BUSY:
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
				title = msgs_data.getText();
			}
			showNotification(context, title, type, msgs_data.getOrder_id());
			sendBroadcast(context, GMsg.ONLINE_BUSY, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_BG_ORDER:
			// 下单类型,0为APP下单，则不刷新订单列表
			String xiadan_type = "";
			if (msgs_data != null) {
				String order_id = msgs_data.getOrder_id();
				int Order_status = msgs_data.getOrder_status();
				db_myordering.onUpdate(order_id, Order_status);
				db_myorder.onUpdate(order_id, Order_status);
				xiadan_type = msgs_data.getType();
			}
			if (xiadan_type != null && xiadan_type.equals("0")) {
				setTitle(
						context,
						type,
						db_myordering.onReadDB_ing(
								msgs_data.getOrder_id()),
						msgs_data.getOrder_id());
				MyOrderingTask.getInstance(context);
			} else {
				onisFindOrdering(db_myordering, type, msgs_data, data,
						jmsg_data);
				// MyOrderingTask.getInstance(context).setOnOrderingFinishListener(this);
				// MyOrderTask.getInstance(context);
			}

			break;
		case GMsg.ONLINE_ENTER_COUPON:
			sendBroadcast(context, type,  data.toString(), jmsg_data);
			
			try {
				JSONObject jmsg = new JSONObject(jmsg_data);
				JSONArray ja_CouponList = jmsg.getJSONArray(GMsg.msg_list);
				showNotification(context,String.format(context.getString(R.string.enter_coupon), ja_CouponList.length()), type, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
        break;
		//通用消息
		case GMsg.OFFICAIL_AA:
			sendBroadcast(context,type, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_SNTIMEOUT:
			sendBroadcast(context,type, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_DRIVERCN:
			sendBroadcast(context,type, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_SNTOQIANGDAN:
			sendBroadcast(context,type, data.toString(), jmsg_data);
			break;
		case GMsg.ONLINE_KF_CHANGE_ORDER:
			showNotification(context, context.getString(R.string.msg_change_order_cotent),
					type, msgs_data.getOrder_id());
			sendBroadcast(context, type, data.toString(),
					jmsg_data);
			break;
		//改价	
		case GMsg.ONLINE_KF_CHANGE_PRICE:
			showNotification(context, String.format(context.getString(R.string.msg_change_price_cotent)
					,FormatUtil.onFormatPrice(msgs_data.old_price)+"元",FormatUtil.onFormatPrice(msgs_data.new_price)+"元"),
					type, msgs_data.getOrder_id());
			sendBroadcast(context, type, data.toString(),
					jmsg_data);
			break;
		case GMsg.ONLINE_KF_CHANGE_PRICE2:
			showNotification(context, String.format(context.getString(R.string.msg_change_price_cotent2)
					,FormatUtil.onFormatPrice(msgs_data.old_mile_price)+"元",FormatUtil.onFormatPrice(msgs_data.new_mile_price)+"元",
					 FormatUtil.onFormatPrice(msgs_data.old_time_price)+"元",FormatUtil.onFormatPrice(msgs_data.new_time_price)+"元"),
					type, msgs_data.getOrder_id());
			sendBroadcast(context, type, data.toString(),
					jmsg_data);
			break;
		//改价	
		case GMsg.ONLINE_KF_CHANGE:
			showNotification(context, context.getString(R.string.msg_change),
					type, msgs_data.getOrder_id());
			sendBroadcast(context, GMsg.ONLINE_KF_CHANGE, data.toString(),
					jmsg_data);
			break;
		case GMsg.ONLINE_SHARECOUPONSUC:
			showNotification(context,msgs_data.getMsg(),
					type, "");
			break;

		}

	}

	public void setTitle(Context context, int type, MyOrderList mMyOrderList,
			String order_id) {
		String start_city = "";
		String end_city = "";
		try {
			 start_city = ToCity2.getCity(mMyOrderList.getLocations().getStart().getAddress());
			 end_city = ToCity2.getCity(mMyOrderList.getLocations().getEnd().getAddress());
		} catch (Exception e) {
		}
		String title = "";
		switch (type) {
		case GMsg.ONLINE_BG_ORDER:
			title = context.getString(R.string.msg_xiadan);
			break;
		case GMsg.ONLINE_PAIDAN:
			title = DateFormat.onCNDateRemove_yyss(mMyOrderList
					.getAppoint_time())
					+String.format(context.getString(R.string.notification_paidan), start_city,end_city);
			break;
		case GMsg.ONLINE_CANCEL:
		case GMsg.ONLINE_KF_CANCEL:
			title = DateFormat.onCNDateRemove_yyss(mMyOrderList
					.getAppoint_time())
					+String.format(context.getString(R.string.notification_cancel), start_city,end_city);
			break;
		case GMsg.ONLINE_GAIPAI:
		case GMsg.ONLINE_KF_GAIPAIL:
		case GMsg.ONLINE_SJ_GAIPAIL: 
			title = DateFormat.onCNDateRemove_yyss(mMyOrderList
					.getAppoint_time())
					+String.format(context.getString(R.string.notification_gaipai), start_city,end_city);
			break;
		case GMsg.ONLINE_ONCAR:
			title = context.getString(R.string.msg_oncar);
			break;
		case GMsg.ONLINE_OFFCAR:
			title = context.getString(R.string.msg_offcar);
			break;
		case GMsg.ONLINE_FINISH:
			title = DateFormat.onCNDateRemove_yyss(mMyOrderList
					.getAppoint_time())
					+String.format(context.getString(R.string.notification_finish), start_city,end_city);
			break;
		}
		showNotification(context, title, type, order_id);
	}

	public void showNotification(Context context, String title, int type,
			String order_id) {
		if (title.equals(""))
			return;
		Intent i;
		if(IsSnQiangDan.isIncludeSnQiangDanLocal(context)!=null){
			i=new Intent();
		}else{
			switch (type) {
				case GMsg.ONLINE_RELOGIN:
					i = new Intent(context, MainActivity.class);
					break;
				case GMsg.ONLINE_ENTER_COUPON:
					i = new Intent(context, CouponActivity.class);
					break;
				default:
					i = new Intent(context, MainActivity.class).putExtra(
							MainMsg.extra_notification, MainMsg.NOTIFICATION_MAIN)
							.putExtra(MainMsg.extra_notification_orderid, order_id);
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 注意本行的FLAG设置
					break;
			}

		}
		int ico = R.drawable.ic_launcher;
		// FLAG_UPDATE_CURRENT
		// 更新数据，如果有多个PendingIntent，且requestCode相同，则会替换为最新extra数据
		PendingIntent pending = PendingIntent.getActivity(context, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);
		// 通知栏
		CharSequence tishi = context.getString(R.string.app_name)+":" + title;
		long when = DateFormat.getTime(); // 获取当前时间

		Notification.Builder builder = new Notification.Builder(context);
//		builder.setContentInfo("补充内容");
		builder.setContentText(title);
		builder.setContentTitle(context.getString(R.string.app_name));
		builder.setSmallIcon(ico);
		builder.setTicker(tishi);
		builder.setAutoCancel(true);
		builder.setWhen(when);
		builder.setContentIntent(pending);
		Notification notification = builder.build();
		// 状态栏管理器（通知栏管理器）
		NotificationManager notificationmanager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);// 获取通知栏管理器
		notificationmanager.notify(3, notification);


//		Notification notification = new Notification(ico, tishi, when);
//		notification.flags |= Notification.FLAG_AUTO_CANCEL;
//		notification.defaults = Notification.DEFAULT_SOUND;
//		// 状态栏
//		notification.setLatestEventInfo(context, context.getString(R.string.app_name), title, pending);
//
//		// 状态栏管理器（通知栏管理器）
//		NotificationManager notificationmanager = (NotificationManager) context
//				.getSystemService(Context.NOTIFICATION_SERVICE);// 获取通知栏管理器
//		notificationmanager.notify(3, notification);
	}

	/**
	 * 发送广播
	 */
	public void sendBroadcast(Context context, int type, String jb,
			String jmsg_data) {
		// 发送广播
		Intent intent = new Intent();
		intent.setAction(MsgBroadcastReceiver.TAG);
		intent.putExtra(MsgBroadcastReceiver.MSG_JSON, jb);
		intent.putExtra(MsgBroadcastReceiver.MSG_TYPE, type);
		intent.putExtra(MsgBroadcastReceiver.MSG_DATA, jmsg_data);
		context.sendBroadcast(intent);
	}

	/**
	 * 注册广播
	 */
	public void registerReceiver(Context context) {
		// 注册广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(MsgBroadcastReceiver.TAG);
		filter.setPriority(Integer.MAX_VALUE);
		context.registerReceiver(mMsgBroadcastReceiver, filter);
	}

	public void unregisterReceiver(Context context) {
		context.unregisterReceiver(mMsgBroadcastReceiver);
	}

	/**
	 * 判断进行中订单是否存在，不存在则加载订单
	 */
	private void onisFindOrdering(final MyOrderingDB db_myordering, final int type,
			final Msgs.Data msgs_data, final JSONObject data, final String jmsg_data) {

		new AsyncTask<Void, Void, Void>() {
			MyOrderList mMyOrderList ;
			@Override
			protected Void doInBackground(Void... arg0) {
				mMyOrderList= db_myordering.onReadDB_ing(
						msgs_data.getOrder_id());
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// 找不到该订单
				if (mMyOrderList.getAppoint_time() == null) {
					LogUtils.e("","找不到订单");
					 MyOrderingTask.getInstance(context,type, jmsg_data,data).setOnOrderingFinishToMessageListener(Online.this);
				}else{
					setTitle(context, type, mMyOrderList, msgs_data.getOrder_id());
					sendBroadcast(context, type, data.toString(), jmsg_data);
				} 

				super.onPostExecute(result);
			}	
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		
		
	}

	/**
	 * 判断订单是否存在，不存在则加载订单
	 */
	private void onisFindOrder(final MyOrderDB db_myorder,final int type,
			final Msgs.Data msgs_data,final JSONObject data,final String jmsg_data) {
		new AsyncTask<Void, Void, Void>() {
			MyOrderList mMyOrderList;
			@Override
			protected Void doInBackground(Void... arg0) {
				 mMyOrderList = db_myorder.onReadDB(
						msgs_data.getOrder_id());
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				// 找不到该订单
				if (mMyOrderList.getAppoint_time() == null) {
					MyOrderTask.getInstance(context,MyOrderActivity.num_all2,type, jmsg_data,data).setOnOrderFinishToMessageListener(Online.this);
				} else {
					setTitle(context, type, mMyOrderList, msgs_data.getOrder_id());
					sendBroadcast(context, type, data.toString(), jmsg_data);
				}
				super.onPostExecute(result);
			}
			
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	@Override
	public void onOrderingFinishToMessage(ArrayList<MyOrderList> list,final int type ,final String jmsg_data,	final JSONObject data) {
		if(list!=null&&jmsg_data!=null){
			final Msgs.Data msgs_data = (Msgs.Data) new JsonBuild().getData(
					Msgs.Data.class, jmsg_data.toString());
			new AsyncTask<Void, Void, Void>() {
				MyOrderList mMyOrderList;
				@Override
				protected Void doInBackground(Void... arg0) {
					MyOrderingDB db_myordering = new MyOrderingDB();// 我的全部订单数据库
					mMyOrderList = db_myordering.onReadDB_ing(
							msgs_data.getOrder_id());
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					setTitle(context, type, mMyOrderList, msgs_data.getOrder_id());
					sendBroadcast(context, type, data.toString(), jmsg_data);
					super.onPostExecute(result);
				}
			  	
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		
	}

	@Override
	public void onOrderFinishToMessage(ArrayList<MyOrderList> list,final int type,final String jmsg_data,	final JSONObject data) {
		if(list!=null&&jmsg_data!=null){
			final Msgs.Data msgs_data = (Msgs.Data) new JsonBuild().getData(
					Msgs.Data.class, jmsg_data.toString());
			new AsyncTask<Void, Void, Void>() {
				MyOrderList mMyOrderList;
				@Override
				protected Void doInBackground(Void... arg0) {
					MyOrderingDB db_myordering = new MyOrderingDB();// 我的全部订单数据库
					mMyOrderList = db_myordering.onReadDB_ing(
							msgs_data.getOrder_id());
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					setTitle(context, type, mMyOrderList, msgs_data.getOrder_id());
					sendBroadcast(context, type, data.toString(), jmsg_data);
					super.onPostExecute(result);
				}
			  	
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		
	}
}
